import { Database, SchemaTableList } from 'src/models/Orm';
import { FieldInfo } from 'mysql';
import { Datasource, Project } from 'src/types';
import { useYmlStore }         from 'stores/ymlStore';
import { useProjectStore }     from 'stores/projectStore';
import { toRaw } from 'vue';

let dataConfig: Datasource;
/**
 *   初始化数据库连接
 * @author qianl
 * @date 2023/8/5 19:58
 * @return string
 * @param data
 */
export const initDatabaseConnection = (data?: Datasource): Promise<string> => {
  return new Promise(async (resolve) => {
    if (data) {
      dataConfig = data;
      resolve(await window.ipcCom.initDatabase(toRaw(data)));
    } else {
      resolve(
        await window.ipcCom.initDatabase(
          toRaw(
            (
              await useProjectStore().project
            ).datasource.find((i: Datasource) => i.selected === true)
          )
        )
      );
    }
  });
};
/**
 *   执行sql
 * @author qianl
 * @date 2023/8/5 20:18
 * @return  Promise<object|null>
 * @param sql
 */
export const stmtDatabase = (sql: string): Promise<object> => {
  return new Promise(async (resolve) =>
  {
    resolve(await window.ipcCom.stmtSql(sql));
  });
};

/**
 *   执行sql
 * @author qianl
 * @date 2023/8/5 20:18
 * @return  Promise<object|null>
 * @param data
 */
export const refreshConnection = (data: Database): Promise<string> => {
  dataConfig = data;
  return new Promise(async (resolve) =>
  {
    resolve(await window.ipcCom.refreshDatabase(data));
  });
};

/**
 *   获取连接池信息
 * @author qianl
 * @date 2023/8/5 20:18
 * @return  Promise<object|null>
 */
export const getConnectionPoolInfo = (): Promise<Database> => {
  return new Promise((resolve) => {
    resolve(dataConfig);
  });
};
/**
 *  展示数据库表
 *
 * @author qianl
 * @date 2023/8/8 15:45
 * @return
 */
export const showTables = (): Promise<SchemaTableList | null> => {
  return new Promise(async (resolve) => {
    const res = await stmtDatabase(
      `SELECT * FROM information_schema.tables WHERE table_schema = '${dataConfig.database}';`
    );
    if (!res) {
      resolve(null);
      return;
    }
    resolve({
      results: res.results as SchemaTableList,
      fields: res.fields as FieldInfo,
    });
  });
};
/**
 *   展示表字段
 * @author qianl
 * @date 2023/8/8 15:46
 * @return
 * @param tables 选择表
 */
export const showColumns = (tables?: string[] | null): Promise<object> => {
  return new Promise(async (resolve) => {
    let tablesParams: string;
    if (!tables || tables?.length <= 0) {
      tablesParams = '';
    } else {
      tablesParams = `and table_name in (${tables
        .map((i) => {
          return `'${i}'`;
        })
        .join(',')})`;
    }
    resolve(
      await stmtDatabase(
        `SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${dataConfig.database}'  ${tablesParams};`
      )
    );
  });
};
/**
 *   展示所有表字段
 * @author qianl
 * @date 2023/8/8 15:46
 * @return
 */
export const showAllColumns = (): Promise<object> => {
  return new Promise(async (resolve) => {
    resolve(
      await stmtDatabase(
        `SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${dataConfig.database}' ORDER BY ORDINAL_POSITION;`
      )
    );
  });
};
